//
//  SWPaymentViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/19.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWPaymentViewController: SWBaseViewController,SWAPIComponent
{
    private var _requisition:SWPurchaseRequisition
    
    private var _wechatPayData:Wechat.PayData?
    private var _orderDetailFetchID:String = ""
    
    private var _successView:UIView = UIView()
    
    
    init(requisition:SWPurchaseRequisition)
    {
        _requisition = requisition
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        SWNotificationCenter.removeObserver(self)
        trace("DEINIT SWPaymentViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
    private func setup()
    {
        
        let nameLable:UILabel = UILabel()
        nameLable.frame = CGRectMake(0, navigationBarBottom, view.width, 60)
        nameLable.textAlignment = .center
        nameLable.numberOfLines = 0
        nameLable.text = _requisition.orderID + "_" + _requisition.payID
        view.addSubview(nameLable)
        
        
        let wechatBtn:UIButton = UIButton(type: .system)
        wechatBtn.setTitle("微信支付", for: .normal)
        wechatBtn.sizeToFit()
        wechatBtn.center = view.center
        wechatBtn.addTarget(self, action: #selector(wechatBtnTapped), for: .touchUpInside)
        view.addSubview(wechatBtn)
        
        createSuccessView()
        
        
        SWNotificationCenter.addObserver(self, selector: #selector(wechatPaySuccessNotification(_:)), name: NSNotification.Name.SWWechatPaySuccess, object: nil)
        SWNotificationCenter.addObserver(self, selector: #selector(wechatPayCancelNotification), name: NSNotification.Name.SWWechatPayCancel, object: nil)
        
        SWNotificationCenter.addObserver(self, selector: #selector(applicationDidBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
        
        
    }
    
    private func createSuccessView()
    {
        _successView.frame = CGRectMake(0, 0, 320, 150)
        _successView.backgroundColor = UIColor.lightGray
        _successView.isHidden = true
        view.addSubview(_successView)
        
        let label = UILabel()
        label.text = "支付成功"
        label.sizeToFit()
        label.center = _successView.bounds.center
        _successView.addSubview(label)
    }
    
    private func wechatPaymentDataFetch()
    {
        let req = SWWechatPaymentDataFetchReq()
        req.payID = _requisition.payID
        req.successCallback = {[weak self] response,_ in
            if let dataRsp = (response as? SWWechatPaymentDataFetchRsp)?.paymentData,
                let data = Wechat.PayData(response:dataRsp)
            {
                self?._wechatPayData = data
                SVProgressHUD.dismiss()
                WeixinHelper.shared().pay(data)
            }
            else
            {
                SVProgressHUD.showError(withStatus: "支付失败，请重试")
            }
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: error.message)
        }
        SVProgressHUD.show(withStatus: "支付中...")
        load(req)
    }
    
    //获取订单详情以检查是否真的付款成功
    private func orderDetailFetch()
    {
        let req = SWOrderDetailFetchReq()
        req.orderID = _requisition.orderID
        req.successCallback = {[weak self] response,_ in
            if let orderRsp = (response as? SWOrderDetailFetchRsp)?.order,
               let order = SWOrder(response: orderRsp),order.status.index >= SWOrderStatus.purchased.index
            {
                let orderID:String = order.orderID ?? ""
                SWNotificationCenter.post(name: NotificationName.PaySuccess, object: nil, userInfo: [SWKey.orderID:orderID])
                
                SVProgressHUD.dismiss()
                self?._successView.isHidden = false
                let intervalID:String = self?._orderDetailFetchID ?? ""
                clearTimeout(intervalID)
            }
            else
            {
                SVProgressHUD.showError(withStatus: "支付未完成")
            }
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: error.message)
        }
        SVProgressHUD.show(withStatus: "处理中...")
        load(req)
    }
    
    @objc private func wechatPaySuccessNotification(_ notification:Notification)
    {
        orderDetailFetch()
    }
    
    @objc private func wechatPayCancelNotification()
    {
        SVProgressHUD.showError(withStatus: "您已取消微信支付")
    }
    
    @objc private func applicationDidBecomeActive()
    {
        //回到前台时，检查是否支付完成
        clearTimeout(_orderDetailFetchID)
        _orderDetailFetchID = setTimeout(1, closure: {[weak self] in
            self?.orderDetailFetch()
        })
    }
    
    @objc private func wechatBtnTapped()
    {
        if let data = _wechatPayData
        {
            WeixinHelper.shared().pay(data)
        }
        else
        {
            wechatPaymentDataFetch()
        }
    }
    
}
